//
//  MineRootViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/2.
//

#import "MineRootViewController.h"
#import "CyCStandardCell.h"
#import "MineHeaderView.h"
#import "UserModel.h"
#import "H5ViewController.h"
#import "MineRequest.h"
#import "ConnectedDeviceCell.h"
#import "ApplyDrivingCell.h"
#import "MileageTableViewCell.h"
#import "TestRideTableCell.h"
#import "UerCenterModel.h"
#import "CarDataCell.h"
#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "CommentTestView.h"

@interface MineRootViewController ()<UITableViewDataSource , UITableViewDelegate>

@property (nonatomic , strong)UITableView *tableView;
@property (nonatomic , strong)NSArray *settings;
@property (nonatomic , strong)MineHeaderView *headerView;
@property (nonatomic, strong) UerCenterModel *model;
@property (strong,nonatomic)NSTimer *timer;

@end

@implementation MineRootViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - NavigationBarHeight)style:(UITableViewStyleGrouped)];
        [_tableView registerClass:[CyCStandardCell class] forCellReuseIdentifier:@"CyCStandardCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"ConnectedDeviceCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ConnectedDeviceCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"ApplyDrivingCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ApplyDrivingCell"];
        [_tableView registerClass:[MileageTableViewCell class] forCellReuseIdentifier:@"MileageTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TestRideTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TestRideTableCell"];
        [_tableView registerClass:[CarDataCell class] forCellReuseIdentifier:@"CarDataCell"];

        _tableView.backgroundColor = COLOR_APP_BACKGROUND;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = HEIGHT_CELL48+MARGIN_MIDDLE;
    }
    return _tableView;
}
- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.settings = @[
        @{@"title":@"骑行历史",@"image":@"icon_mine_history"},
        @{@"title":@"健康见解",@"image":@"icon_mine_health"},
        @{@"title":@"推荐",@"image":@"icon_mine_recomment"}
    ];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.ce_y, SCREEN_W, 210+SafeAreaTopHeight)];
    self.headerView = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 210+SafeAreaTopHeight)];
    [headerView addSubview:self.headerView];
    [self.headerView.carSelectBtn addTarget:self action:@selector(selectCarAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headerView.carSettingBtn addTarget:self action:@selector(setting) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.headPhotoBtn addTarget:self action:@selector(clickedUserPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.carEidtBtn addTarget:self action:@selector(clickedUserPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.carRecommentBtn addTarget:self action:@selector(clickedRecomment) forControlEvents:UIControlEventTouchUpInside];

    self.tableView.tableHeaderView = headerView;
    
    [self.view addSubview:self.tableView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    self.tableView.mj_header = header;
    _timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(loadData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    [_timer fire];
        
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self loadData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
}

- (void)updateHeaderView {
    [self.headerView.headerImageView sd_setImageWithURL:[NSURL URLWithString:self.model.userinfo.avatar] placeholderImage:[UIImage imageNamed:@"icon_mine_head"]];
    self.headerView.nameLB.text = self.model.userinfo.nickname;
    self.headerView.numLB.text = self.model.userinfo.username;
    self.headerView.carRecommentLB.text = [NSString stringWithFormat:@"勋章%@",self.model.userinfo.level];
    self.headerView.currentCarLB.hidden = self.model.equipment == nil;
    self.headerView.carSelectBtn.hidden = self.model.equipment == nil;
    self.headerView.downimview.hidden = self.model.equipment == nil;

}

- (void)loadData {
    [MineRequest getUserInfoMessageWithEid:@"" result:^(UerCenterModel * _Nonnull model) {
        [self.tableView.mj_header endRefreshing];
        self.model = model;
        [self updateHeaderView];
        [self.tableView reloadData];
    }];
}
- (void)clickedUserPhoto {
    H5ViewController *vc = [[H5ViewController alloc] init];
    vc.url = Cyc_WEBURL_USERINFO;
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)setting {
    H5ViewController *vc = [[H5ViewController alloc] init];
    vc.url = Cyc_WEBURL_SETTINGS;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)selectCarAction {
    H5ViewController *vc = [[H5ViewController alloc] init];
    vc.url = Cyc_WEBURL_CHOOSECAR;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickedRecomment {
    H5ViewController *vc = [[H5ViewController alloc] init];
    vc.url = Cyc_WEBURL_XUNZHANG;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ==== datasource代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.settings.count+4;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 0){
        return CGFLOAT_MIN;
    }
    if (section == 2) {
        if (self.model.tryride == nil) {
            return CGFLOAT_MIN;
        }
        return [self.model.tryride.status intValue] == 3 && [self.model.tryride.cstatus intValue] == 3 && [self.model.tryride.isend intValue] == 1 ? CGFLOAT_MIN : MARGIN_MIDDLE;
    }
    return MARGIN_MIDDLE;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.section == 0){
        return self.model.equipment == nil ? 85 : 145;
    }
    if(indexPath.section == 1){
        if (self.model.tryride == nil) {
            return 85;
        }
        return [self.model.tryride.status intValue] == 3 && [self.model.tryride.cstatus intValue] == 3 && [self.model.tryride.isend intValue] == 1 ? 85 : CGFLOAT_MIN;
    }
    if(indexPath.section == 2){
        if (self.model.tryride == nil) {
            return CGFLOAT_MIN;
        }
        return [self.model.tryride.status intValue] == 3 && [self.model.tryride.cstatus intValue] == 3 && [self.model.tryride.isend intValue] == 1 ? CGFLOAT_MIN : 240;
    }

    if(indexPath.section == 3){
        return 140;
    }
    return 48;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        if(self.model.equipment == nil){
            ConnectedDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConnectedDeviceCell" forIndexPath:indexPath];
            if (!cell) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"ConnectedDeviceCell" owner:self options:nil] lastObject];
            }
            cell.block = ^(NSString * _Nonnull device) {
                H5ViewController *vc = [[H5ViewController alloc] init];
                vc.url = Cyc_WEBURL_CHOOSECAR;
                [self.navigationController pushViewController:vc animated:YES];
            };
            return cell;
        }else {
            CarDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarDataCell" forIndexPath:indexPath];
            cell.model = self.model.equipment;
            return cell;
        }
    }
    if(indexPath.section == 1) {
        ApplyDrivingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ApplyDrivingCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ApplyDrivingCell" owner:self options:nil] lastObject];
        }
        cell.block = ^(NSString * _Nonnull model) {
            BaseTabBarController *vc = (BaseTabBarController *)appDelegate.getKeyWindowRootViewController;
                                [vc selectIndex:4];
        };
        if (self.model.tryride == nil) {
            cell.hidden = NO;
        }else {
            if ([self.model.tryride.status intValue] == 3 && [self.model.tryride.cstatus intValue] == 3 && [self.model.tryride.isend intValue] == 1) {
                cell.hidden = NO;
            } else {
                cell.hidden = YES;
            }
        }
        return cell;
    }
    if (indexPath.section == 2) {
        TestRideTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestRideTableCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"TestRideTableCell" owner:self options:nil] lastObject];
        }
        cell.acceptBlock = ^(NSString * _Nonnull str) {
            [MineRequest acceptRideWithId:self.model.tryride.id Result:^(BOOL ret) {
                [self loadData];
                if ([self.model.tryride.issqr intValue] == 2) { // 被申请人
                    [self alertViewTitle:@"提示" message:@"请在推荐中处理" title:@"确认" block:^{
                    }];
                }
            }];
        };
        cell.refuseBlock = ^(BOOL isRefuse) {
            if (isRefuse) {
                [MineRequest refuseRideWithId:self.model.tryride.id Result:^(BOOL ret) {
                    [self loadData];
                }];
            }else {
                [CommentTestView CommentWith:NSObject.getKeyWindowRootViewController Complection:^(NSString * _Nonnull content) {
                    [MineRequest commentTryrideWithId:self.model.tryride.id content:content Result:^(BOOL ret) {
                        if (ret) {
                            [self showHudTipStr:@"评论成功"];
                        }
                        [MineRequest endRideWithId:self.model.tryride.id Result:^(BOOL ret) {
                        }];
                    }];
                    [NSObject.getKeyWindowRootViewController gq_removeBgView];
                }];

            }
        };
        cell.model = self.model.tryride;
        
        if (self.model.tryride == nil) {
            cell.hidden = YES;
        }else {
            if ([self.model.tryride.status intValue] == 3 && [self.model.tryride.cstatus intValue] == 3 && [self.model.tryride.isend intValue] == 1) {
                cell.hidden = YES;
            } else {
                cell.hidden = NO;
            }
        }

        return cell;

    }
    if(indexPath.section == 3) {
        MileageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MileageTableViewCell" forIndexPath:indexPath];
        cell.todayArr = self.model.todayArr;
        return cell;
    }
    
    CyCStandardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CyCStandardCell" forIndexPath:indexPath];
    cell.cellType = CycStandardCellTypeDefult;
    [cell setCurrentIndex:0 cellCount:1];
    
    NSDictionary *setting = self.settings[indexPath.section-4];
    cell.titleLB.text = setting[@"title"];
    cell.imView.image = [UIImage imageNamed:setting[@"image"]];
    
    return cell;
}

#pragma mark ==== delegate代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3) {
        return;
    }
    H5ViewController *vc = [[H5ViewController alloc] init];
    if (indexPath.section == 4) {
        vc.url = Cyc_WEBURL_RIDEHISTORY;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.section == 5) {
        vc.url = Cyc_WEBURL_DRIVEHEALTH;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.section == 6) {
        vc.url = Cyc_WEBURL_TRYRIDE;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
